<?php

namespace App\Exports;

use App\Order;
use App\OrderDetail;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\StringValueBinder;

class PrintExport extends StringValueBinder implements FromCollection,WithHeadings
{
    public $start_time;
    public $end_time;
    public function __construct($start_time,$end_time)
    {
        $this->start_time=$start_time;
        $this->end_time=$end_time;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $arr=collect([]);
        $start_time=$this->start_time;
        $end_time=$this->end_time;
        $result=Order::where([['status','=',1],['deliveryStatus','=',1],["receivingStatus",'=',0]])
            ->when($this->start_time,function ($query)use ($start_time){
            $query->where('created_at','>=',$start_time);
        })->when($end_time,function ($query)use ($end_time){
            $query->where('created_at','<=',$this->end_time);
        })->groupBy("tracking_no")->latest()->get()->toArray();
        foreach ($result as $key=>$value){
            $goods="";
            $count=0;
            $detail=OrderDetail::where('order_id',$value['order_number'])->get();

            foreach ($detail as $k=>$v){
                $goods.=$v["goods_name"]." ".$v["sku"].";";
                $count+=$v['number'];
            }
            $data=[
                "order_id"=>$value['order_number'],
                "company"=>"",
                "consignee"=>$value["address_consignee"],
                "tel"=>"",
                "phone"=>$value["address_phone_number"],
                "address"=>$value['address_province'].$value['address_city'].$value['address_area'].$value['address_detail'],
                "names"=>$goods,
                "count"=>$count,
                "weight"=>1,
                "remark"=>"",
                "22"=>"寄付月结",
                "33"=>"顺丰标快"

            ];
            $arr->push($data);
        }

        return $arr;
    }
    public function headings(): array
    {
        return [
            "用户订单号",
            "收件公司",
            "收件人",
            "收件电话",
            "收件手机",
            "收件详细地址",
            "托寄物内容",
            "托寄物数量",
            "包裹重量",
            "寄方备注",
            "运费付款方式",
            "业务类型",
        ];
    }
}
